package com.car.spdier.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.car.spdier.service.UserService;
import com.car.spdier.service.dao.entity.SqlTable;
import com.car.spdier.service.dao.entity.UserBase;
import com.comm.db.jdbc.JdbcUtil;

public class UserServiceImpl implements UserService {

	public int getUserIdByCarNumber(String carNo, String city) {
		UserBase userBase = new UserBase();
		List<UserBase> users=getUserBase(  userBase );
		if(users!=null&&users.size()>0){
		   userBase=users.get(0);
		   if(!isBlank(userBase)){
			   return userBase.getUserId();
		   }
		}
		return 0;
	}
   
	public List<UserBase> getUserBase(UserBase userBase) {
		List prams = new ArrayList();
		StringBuffer SqlBuf = new StringBuffer(SqlTable.QUERY_TUSER_BASE);
		SqlBuf.append(" where 1==1 ");
		if (!isBlank(userBase.getCarNo()) && !isBlank(userBase.getCarNoCity())) {
			SqlBuf.append(" AND car_no=? AND car_no_city=? ");
			prams.add(userBase.getCarNo());
			prams.add(userBase.getCarNoCity());
		}
		if (!isBlank(userBase.getEngineCode())) {
			SqlBuf.append(" AND engine_code=? ");
			prams.add(userBase.getEngineCode());
		}
		if (!isBlank(userBase.getDriveingNo())) {
			SqlBuf.append(" AND driving_no=? ");
			prams.add(userBase.getDriveingNo());
		}
		SqlBuf.append(" LIMIT 0, 20 ");
		List<Map<String, Object>> list = JdbcUtil.getListMap(SqlBuf.toString(),
				prams);
		if (list != null && list.size() > 0) {
			return listToUsers(list);
		}
		return new ArrayList();
	}

	private List<UserBase> listToUsers(List<Map<String, Object>> list) {
		List<UserBase> users=new ArrayList();
		UserBase user = null;
		for (Map<String, Object> map : list) {
			if (map != null) {
				user = new UserBase();
				if (!isBlank(map.get(UserBase.car_no))) {
					user.setCarNo(map.get(UserBase.car_no).toString());
				}
				if (!isBlank(map.get(UserBase.car_no_city))) {
					user.setCarNoCity(map.get(UserBase.car_no_city).toString());
				}
				if (!isBlank(map.get(UserBase.driving_no))) {
					user.setDriveingNo(map.get(UserBase.driving_no).toString());
				}
				if (!isBlank(map.get(UserBase.engine_code))) {
					user
							.setEngineCode(map.get(UserBase.engine_code)
									.toString());
				}
				user.setUserId(Integer.parseInt(map.get(UserBase.user_id)
						.toString()));
				users.add(user);
			}

		}
		return users;
	}

	public void stroeTUserBase() {
		// TODO Auto-generated method stub

	}

	private boolean isBlank(Object obj) {

		if (null == obj || obj.toString().trim().length() == 0) {
			return true;
		}
		return false;

	}

	private boolean isBlank(String string) {
		if (null == string || string.trim().length() == 0) {
			return true;
		}
		return false;
	}

}
